import subprocess
import datetime


def execute_script(script_path, params: []):
    try:
        # 执行 Shell 脚本
        result = subprocess.run(['bash', script_path] + params, capture_output=True, text=True)

        # 获取脚本的输出
        stdout = result.stdout.strip()

        # 检查脚本是否成功执行
        if result.returncode == 0:
            return stdout
        else:
            print("脚本执行失败", result.stderr.strip())
            raise OSError("执行错误:" + str(result.returncode))

    except subprocess.CalledProcessError as e:
        print(f"Error: {e}")


def execute_script_with_output(script_path, params: []):
    try:
        output_line = []
        # 使用 subprocess.Popen 执行 Shell 脚本
        process = subprocess.Popen(
            ['bash', script_path] + params,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True
        )
        # 逐行读取输出并记录到文件中
        for line in iter(process.stdout.readline, ''):
            output_line.append(line)

        process.stdout.close()
        process.wait()

        print(datetime.datetime.now(), " script output: ")
        [print(line, end="") for line in output_line]

        # 执行是否成功
        if process.returncode == 0:
            return output_line[-1] if len(output_line) > 0 else "0"
        else:
            raise OSError("执行错误:")

    except subprocess.CalledProcessError as e:
        print(f"Error: {e}")
